/*
 * uart.c
 *
 *  Created on: 2022年2月28日
 *      Author: li
 */
#include <string.h>

#include "esp_system.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "driver/uart.h"
#include "driver/gpio.h"

void tts_init(void)
{
	const uart_config_t uart_config =
	{ .baud_rate = 9600, .data_bits = UART_DATA_8_BITS, .parity =
			UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1, .flow_ctrl =
			UART_HW_FLOWCTRL_DISABLE, .source_clk = UART_SCLK_APB, };
	// We won't use a buffer for sending data.
	uart_driver_install(UART_NUM_1, CONFIG_TTS_BUFFER_SIZE * 2, 0, 0, NULL, 0);
	uart_param_config(UART_NUM_1, &uart_config);
	uart_set_pin(UART_NUM_1, CONFIG_TTS_TX_GPIO, CONFIG_TTS_RX_GPIO, UART_PIN_NO_CHANGE,
			UART_PIN_NO_CHANGE);
}

void tts_speak(char cn_text[], int len)
{
	char Frame_Info[300];
	char ecc = 0;  				//定义校验字节
	int i = 0;
	Frame_Info[0] = 0xFD; 		//构造帧头FD
	Frame_Info[1] = 0x00; 		//构造数据区长度的高字节
	Frame_Info[2] = len + 3; 	//构造数据区长度的低字节
	Frame_Info[3] = 0x01; 		//构造命令字：合成播放命令
	Frame_Info[4] = 0x01;  		//构造命令参数：背景音乐设定

	for (i = 0; i < 5; i++)   			//依次发送构造好的5个帧头字节
	{
		ecc = ecc ^ (Frame_Info[i]);	//对发送的字节进行异或校验
	}

	for (i = 0; i < len; i++)   		//依次发送待合成的文本数据
	{
		ecc = ecc ^ (cn_text[i]); 		//对发送的字节进行异或校验
	}
	memcpy(&Frame_Info[5], cn_text, len);
	Frame_Info[5 + len] = ecc;
	for (i = 0; i < 1; i++)
	{
		uart_write_bytes(UART_NUM_1, Frame_Info, 5 + len + 1);
	}
}
